//
//  PositionViewController.m
//  SelfDriving
//
//  Created by apple on 16/8/22.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "PositionViewController.h"
#import "CustomAnnotationView.h"
#import "BusinessService+User.h"
#import <CoreLocation/CoreLocation.h>
#import <AVFoundation/AVFoundation.h>
#import "MyLatLng.h"
#import "SphereMenu.h"
@interface PositionViewController ()<UIAlertViewDelegate,CLLocationManagerDelegate,UIActionSheetDelegate,UIActionSheetDelegate,MAMapViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scroll;
@property (weak, nonatomic) IBOutlet UILabel *titleLable;
@property (weak, nonatomic) IBOutlet UIView *gbview;
@property (nonatomic, retain) NSTimer  *controlMicTimer;
@property (weak, nonatomic) IBOutlet UIButton *mic_btn;
@property (weak, nonatomic) IBOutlet UIView *pview;
@property (weak, nonatomic) IBOutlet UIButton *qiehuanBtn;
@property (weak, nonatomic) IBOutlet UIView *leidaView;
@property (weak, nonatomic) IBOutlet MAMapView *mapView;


@property (strong, nonatomic) UIImageView *arrowImageView;

@property ( strong , nonatomic ) AVCaptureDevice * device;
@property ( strong , nonatomic ) AVCaptureDeviceInput * input;
@property ( strong , nonatomic ) AVCaptureMetadataOutput * output;
@property ( strong , nonatomic ) AVCaptureSession * session;
@property ( strong , nonatomic ) AVCaptureVideoPreviewLayer * preview;
@end

@implementation PositionViewController
{
    NSTimer *timer;
    
    int isqiangmai;//是否是抢麦
    int istablescoolr;
    int isbofgang;
    NSString *meetingNumber;// 蓉联会议ID
    
    BOOL isMute;//管理员开关麦
    NSInteger controlMicBtnStatus; //0:未控麦状态 1:控麦中 2:控麦成功
    NSInteger speakTimeInterval;
    //场景模式
    NSMutableArray *d;
    NSMutableArray *db;
    NSMutableArray *b;
    NSMutableArray *xb;
    NSMutableArray *x;
    NSMutableArray *xn;
    NSMutableArray *n;
    NSMutableArray *dn;
    UIView *mapview;
    UILabel *la;
    NSMutableDictionary *map;
    NSMutableArray *ary;
    CLLocationManager *locationManager;
    UIImageView *leidaimg;
    int isdw;
    LoginResponseModel *userd;
}
-(void)viewWillAppear:(BOOL)animated{
    _mapView.delegate = self;
    self.navigationController.navigationBarHidden = YES;
    [self initTxView];
}
-(void)viewWillDisappear:(BOOL)animated{
    [timer invalidate];
    _mapView.delegate = nil;
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gongxiangzhongzhi:) name:@"gongxiangzhongzhi" object:nil];
    _pview.hidden = YES;
    _gbview.layer.opacity = 0.5;
    [[ECDevice sharedInstance].VoIPManager enableLoudsSpeaker:YES];
    
    NSMutableDictionary *dic = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
    
    CLLocationCoordinate2D coors;
    coors.latitude = [[dic objectForKey:@"lat"] floatValue];
    coors.longitude = [[dic objectForKey:@"lng"] floatValue];
    
    _mapView.showsUserLocation = YES;
    self.mapView.userTrackingMode  = MAUserTrackingModeNone;
    //    _map.showsUserLocation = YES;
    //    _map.hidden = YES;
    //    _map.zoomLevel = 16;//地图显示比例
    //    _map.rotateEnabled = NO; //设置是否可以旋转
    //    locService = [[BMKLocationService alloc]init];
    //    locService.delegate = self;
    //    [locService startUserLocationService];
    
    
    
    timer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(initTxView) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
         ECCreateMeetingParams *params =[[ECCreateMeetingParams alloc]init];
        params.meetingType = ECMeetingType_MultiVoice;
        params.meetingName= _user.id;
        params.meetingPwd=@"yimisns";
        //        params.square= 1;
        params.autoClose = NO;
        params.autoJoin = YES;
        params.autoDelete = YES;
        params.voiceMod = 3;
        params.keywords = @"业务属性";
        if(_isjon||[_user.uid intValue] != [[AppDelegate shareDelegate].user.uid intValue]){//非创建者
            [[ECDevice sharedInstance].meetingManager joinMeeting:_meetingNumbers ByMeetingType:ECMeetingType_MultiVoice andMeetingPwd:@"yimisns" completion:^(ECError *error, NSString *meetingNumber) {
                if (error.errorCode == ECErrorType_NoError)
                {
                    //                [[NSNotificationCenter defaultCenter ]postNotificationName:@"zhibokaiqi" object:nil];
                    [SVProgressHUD showImage:nil status:@"加入会议成功"];
                }
                else
                {
                    NSString *msg = @"加入位置共享失败，请稍后再试！";
                    [SVProgressHUD showErrorWithStatus:error.errorDescription.length==0?msg:error.errorDescription];
                    
                    NSLog(@"加入会议失败");
                    //                        [SVProgressHUD showImage:nil status:@"进入直播失败"];
                }
            }];
        }else{
            [[ECDevice sharedInstance].meetingManager createMultMeetingByType:params completion:^(ECError *error, NSString *meetingNumbers) {
                //meetingNo 创建会议回调的会议号
                if (error.errorCode == ECErrorType_NoError)
                {
                    _meetingNumbers = meetingNumbers;
                    NSLog(@"创建成功之后->meetingNumbers->%@",meetingNumbers);
                    NSLog(@"会议创建成功，请讲话");
                    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
                    [dic setObject:_user.id forKey:@"groupId"];
                    [dic setObject:[[_user.userlist firstObject]objectForKey:@"nickname"] forKey:@"nickname"];
                    [dic setObject:meetingNumbers forKey:@"meetingNumbers"];
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"sendgongxiang" object:dic];
                }
                else
                {
                    [SVProgressHUD dismiss];
                    NSString *msg = @"开启位置共享失败，请稍后再试！";
                    [SVProgressHUD showErrorWithStatus:error.errorDescription.length==0?msg:error.errorDescription];
                    NSLog(@"会议创建失败，稍后重试");
                }
            }];
     }
    [_mic_btn addTarget:self action:@selector(maiAction:) forControlEvents:UIControlEventTouchUpInside];
    [self initCjmsView];
}

#pragma mark 直播说话开关/抢麦
- (IBAction)maiAction:(UIButton *)sender {
    //    if([_user.uid intValue] == [[AppDelegate shareDelegate].user.uid intValue]){
    isMute = !isMute;
    [[ECDevice sharedInstance].VoIPManager setMute:isMute];
    if (isMute) {
        [SVProgressHUD showImage:nil status:@"麦克风已关闭"];
    }else{
        [SVProgressHUD showImage:nil status:@"所有人员可听见你讲话"];
    }
    //    }
}
#pragma mark 切换场景模式OR地图模式
- (IBAction)qiehuanMoshi:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        _mapView.hidden = YES;
        _pview.hidden = NO;
        _leidaView.hidden = NO;
    }else{
        _mapView.hidden = NO;
        _pview.hidden = YES;
        _leidaView.hidden = YES;
    }
}
#pragma mark 初始化头像
-(void)initTxView{
    for (UIView *view in  [_scroll subviews]) {
        [view removeFromSuperview];
    }
    NSMutableDictionary *dic = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
    [dic setObject:_user.id forKey:@"groupId"];
    [[BusinessService shareInstance]posshare_lastUserHeads:dic
                                                   success:^(id result) {
                                                       NSMutableArray *data = result;
                                                       _ary = [[NSMutableArray alloc]init];
                                                       _ary = data;
                                                       _titleLable.text = [NSString stringWithFormat:@"%d个人在共享位置",data.count];
                                                       int h = 0;
                                                       for (int i = 0; i<data.count; i++) {
                                                           LoginResponseModel *user = [data objectAtIndex:i];
                                                           CLLocationCoordinate2D coors;
                                                           coors.latitude = [user.lat floatValue];
                                                           coors.longitude = [user.lng floatValue];
                                                           //                                                           if ([user.uid intValue]!=[_user.uid intValue]) {
                                                           MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
                                                           pointAnnotation.coordinate = coors;
                                                           pointAnnotation.title = [NSString stringWithFormat:@"%@,%d",user.nickname,i];
                                                           pointAnnotation.subtitle = [ValidateHelper DistanceFormat:user.distance];
                                                           [_mapView addAnnotation:pointAnnotation];
                                                           //                                                           }
                                                           UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(h, 10, 50, 50)];
                                                           [ValidateHelper setImage:user.headsmall img:img istoux:YES];
                                                           img.layer.cornerRadius = 25;
                                                           img.clipsToBounds = YES;
                                                           img.layer.borderColor = [UIColor whiteColor].CGColor;
                                                           img.layer.borderWidth = 1;
                                                           [_scroll addSubview:img];
                                                           h = h + 55;
                                                       }
                                                       [self refdata];
                                                       _scroll.contentSize = CGSizeMake(h, 0);
                                                   } failure:^(id result) {
                                                   }];
    
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    //        if (_mapView.userLocation == annotation) {
    //            return nil;
    //        }
    
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *customReuseIndetifier = @"customReuseIndetifier";
        CustomAnnotationView *annotationView = (CustomAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:customReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[CustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:customReuseIndetifier];
            // must set to NO, so we can show the custom callout view.
            annotationView.canShowCallout = NO;
            annotationView.draggable = YES;
            annotationView.calloutOffset = CGPointMake(0, -5);
        }
        MAPointAnnotation *pointAnnotation = (MAPointAnnotation *)annotation;
        
        NSArray *array = [pointAnnotation.title componentsSeparatedByString:@","];
        LoginResponseModel *user = [_ary objectAtIndex:[[array lastObject] intValue]];
        UIImageView *img1 = [[UIImageView alloc]init];
        if (user==nil) {
            [img1 sd_setImageWithURL:[NSURL URLWithString:userd.headsmall]
                    placeholderImage:[UIImage imageNamed:@"mrtx"]];
        }else{
            [img1 sd_setImageWithURL:[NSURL URLWithString:user.headsmall]
                    placeholderImage:[UIImage imageNamed:@"mrtx"]];
        }
        img1.image = [UIImage createRoundedRectImage:img1.image size:CGSizeMake(60, 60) radius:30];
        
        annotationView.image = img1.image;
        //    annotationView.name  = user.nickname;
        annotationView.backgroundColor = [UIColor clearColor];
        annotationView.enabled = NO;
        return annotationView;
    }
    return nil;
}

- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view
{
    /* Adjust the map center in order to show the callout view completely. */
    
}

//-(BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation{
//    static NSString *ID=@"annoView";
//    BMKAnnotationView *annoView = [mapView dequeueReusableAnnotationViewWithIdentifier:ID];
//    if (annoView==nil) {
//        annoView=[[BMKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:ID];
//        //点击大头针出现信息（自定义view的大头针默认点击不弹出）
//        annoView.canShowCallout=YES;
//    }
//    //再传递一次annotation模型（赋值）
//    annoView.annotation = annotation;
//
//    WPAnnotation *anno = annotation;
//    UIImageView *img = [[UIImageView alloc]init];
//    [ValidateHelper setImage:anno.icon img:img istoux:YES];
//    img.image = [UIImage createRoundedRectImage:img.image size:CGSizeMake(80, 80) radius:40];
//    annoView.image = img.image;
//    return annoView;
//
//}
#pragma  mark 高德
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation
{
    if (updatingLocation)
    {
        if (isdw==0) {
            _mapView.centerCoordinate = userLocation.location.coordinate;
            [[AppDelegate shareDelegate]refuser:_user.uid success:^(id as) {
                userd = as;
                MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
                pointAnnotation.coordinate = userLocation.location.coordinate;
                pointAnnotation.title = [NSString stringWithFormat:@"%@,%d",_user.name,0];
                pointAnnotation.subtitle = [ValidateHelper DistanceFormat:_user.distance];
                [_mapView addAnnotation:pointAnnotation];
                isdw = 1;
            }];
        }
        //        WPAnnotation *anno0=[[WPAnnotation alloc]init];
        //        CLLocationCoordinate2D coors;
        //        coors.latitude = userLocation.location.coordinate.latitude;
        //        coors.longitude = userLocation.location.coordinate.longitude;
        //        anno0.coordinate = coors;
        //        anno0.title = _user.nickname;
        //        anno0.subtitle = [ValidateHelper DistanceFormat:_user.distance];
        //        anno0.icon = _user.headsmall;
        //        [_mapView addAnnotation:anno0];
        //发起附近周边搜索
    }
}
//-(void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{
////    _map.hidden = NO;
//
//
//
//    BMKCoordinateRegion viewRegion = BMKCoordinateRegionMake(userLocation.location.coordinate, BMKCoordinateSpanMake(0.02f,0.02f));
////    BMKCoordinateRegion adjustedRegion = [_map regionThatFits:viewRegion];
////    [_map setRegion:adjustedRegion animated:YES];
//    //    [_map updateLocationData:userLocation];//显示按钮
////    [locService stopUserLocationService];
//
//
//
//
//
//
//
////    //初始化检索对象
////    _searcher =[[BMKGeoCodeSearch alloc]init];
////    _searcher.delegate = self;
////    BMKReverseGeoCodeOption *geoCodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
////    geoCodeSearchOption.reverseGeoPoint = userLocation.location.coordinate;
////    BOOL flag = [_searcher reverseGeoCode:geoCodeSearchOption];
////    if(flag)
////    {
////        NSLog(@"geo检索发送成功");
////    }
////    else
////    {
////        NSLog(@"geo检索发送失败");
////    }
////    [SVProgressHUD dismiss];
//}
-(void)gongxiangzhongzhi:(NSNotification *)not{
    [SVProgressHUD showImage:nil status:@"位置共享被解散"];
    [[ECDevice sharedInstance].meetingManager exitMeeting];
    [_deleagte zhongzhi];
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark 返回
- (IBAction)backAction:(UIButton *)sender {
//    if([_user.uid intValue] != [[AppDelegate shareDelegate].user.uid intValue]){//非管理员
//    }
    if (_ary.count == 1) {
//        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"当前共享就您一个人，确定关闭位置共享?" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
//        [alert show];
    [self.navigationController popViewControllerAnimated:YES]; //xhw2018-2-11改://位置共享中，右上角按钮是退出当前页面，不结束共享会话
    }else{
//        [[ECDevice sharedInstance].meetingManager exitMeeting]; //位置共享中，右上角按钮是退出当前页面，不结束共享会话
        [self.navigationController popViewControllerAnimated:YES];
    }
}
#pragma  mark 终止
- (IBAction)jiesuAction:(UIButton *)sender {
    if([_user.uid intValue] != [[AppDelegate shareDelegate].user.uid intValue]){//非管理员
        [[ECDevice sharedInstance].meetingManager exitMeeting];
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"确定关闭当前实时位置共享?" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        [alert show];
    }
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        NSLog(@"进到这里了2018-2-11");
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
        [dic setObject:_user.id forKey:@"groupId"];
        [[BusinessService shareInstance]posshare_quitGroup:dic success:^(id result) {
            NSLog(@"解散会议->meetingNumbers->%@",_meetingNumbers);
            [[ECDevice sharedInstance].meetingManager deleteMultMeetingByMeetingType:ECMeetingType_MultiVoice andMeetingNumber: _meetingNumbers completion:^(ECError *error, NSString *meetingNumber) {
                if (error.errorCode == ECErrorType_NoError)
                {
                    [_deleagte zhongzhi];
                    NSLog(@"解散会议成功");
                    [self.navigationController popViewControllerAnimated:YES];
                    return ;
                }
                else
                {
//                    [SVProgressHUD showErrorWithStatus:@"终止失败"]; //xhw2018-2-12注释
                    NSLog(@"解散会议失败");
                }
            }];
        } failure:^(id result) {
            [SVProgressHUD showErrorWithStatus:result];
        }];
    }
}


#pragma mark  场景模式

-(CGPoint)calcCircleCoordinateWithCenter:(CGPoint) center  andWithAngle : (CGFloat) angle andWithRadius: (CGFloat) radius{
    CGFloat x2 = radius*cosf(angle*M_PI/180);
    CGFloat y2 = radius*sinf(angle*M_PI/180);
    return CGPointMake(center.x+x2, center.y-y2);
}
-(int)getRandomNumber:(int)from to:(int)to
{
    return (int)(from + (arc4random() % (to - from + 1)));
}
#pragma mark 更新共享人数
-(void)refdata{
    _isuser = YES;
    d = [[NSMutableArray alloc]init];
    db = [[NSMutableArray alloc]init];
    b = [[NSMutableArray alloc]init];
    xb = [[NSMutableArray alloc]init];
    x = [[NSMutableArray alloc]init];
    xn = [[NSMutableArray alloc]init];
    n = [[NSMutableArray alloc]init];
    dn = [[NSMutableArray alloc]init];
    ary = [[NSMutableArray alloc]init];
    [ary addObjectsFromArray:_ary];
    MyLatLng *m1 = [[MyLatLng alloc]init];//当前坐标
    NSMutableDictionary *userLocation = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
    
    [m1 initData:[[NSString stringWithFormat:@"%@",[userLocation objectForKey:@"lat"]] floatValue] ln:[[NSString stringWithFormat:@"%@",[userLocation objectForKey:@"lng"]] floatValue]];
    for (int i = 0; i<ary.count; i++) {
        LoginResponseModel *user =  [ary objectAtIndex:i];
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
        if(_isuser){
            [dic setObject:user.nickname forKey:@"name"];
            [dic setObject:user.uid forKey:@"id"];
            [dic setObject:user.headsmall forKey:@"headsmall"];
        }else{
            [dic setObject:user.name forKey:@"name"];
            [dic setObject:user.id forKey:@"id"];
        }
        [dic setObject:user.lng forKey:@"lo"];
        [dic setObject:user.lat forKey:@"la"];
        [dic setObject:user.distance forKey:@"distance"];
        MyLatLng *m2= [[MyLatLng alloc]init];
        [m2 initData:[[dic objectForKey:@"la"] floatValue] ln:[[dic objectForKey:@"lo"]floatValue]];
        NSMutableDictionary * direction = [ValidateHelper outFangxiang:m1 b:m2];
        NSString *w = [direction objectForKey:@"p"];
        NSMutableDictionary *newdic = [[NSMutableDictionary alloc]init];
        [newdic addEntriesFromDictionary:direction];
        [newdic addEntriesFromDictionary:dic];
        dic = newdic;
        if ([w isEqualToString:@"东"]) {
            CGPoint center = [self setxy];
            [dic setObject:[NSString stringWithFormat:@"%f",center.x] forKey:@"x"];
            [dic setObject:[NSString stringWithFormat:@"%f",center.y] forKey:@"y"];
            [d addObject:dic];
        }
        if ([w isEqualToString:@"东北"]) {
            CGPoint center = [self setxy];
            [dic setObject:[NSString stringWithFormat:@"%f",center.x] forKey:@"x"];
            [dic setObject:[NSString stringWithFormat:@"%f",center.y] forKey:@"y"];
            [db addObject:dic];
        }
        if ([w isEqualToString:@"北"]) {
            CGPoint center = [self setxy];
            [dic setObject:[NSString stringWithFormat:@"%f",center.x] forKey:@"x"];
            [dic setObject:[NSString stringWithFormat:@"%f",center.y] forKey:@"y"];
            [b addObject:dic];
        }
        if ([w isEqualToString:@"西北"]) {
            CGPoint center = [self setxy];
            [dic setObject:[NSString stringWithFormat:@"%f",center.x] forKey:@"x"];
            [dic setObject:[NSString stringWithFormat:@"%f",center.y] forKey:@"y"];
            [xb addObject:dic];
        }
        if ([w isEqualToString:@"西"]) {
            CGPoint center = [self setxy];
            [dic setObject:[NSString stringWithFormat:@"%f",center.x] forKey:@"x"];
            [dic setObject:[NSString stringWithFormat:@"%f",center.y] forKey:@"y"];
            [x addObject:dic];
        }
        if ([w isEqualToString:@"西南"]) {
            CGPoint center = [self setxy];
            [dic setObject:[NSString stringWithFormat:@"%f",center.x] forKey:@"x"];
            [dic setObject:[NSString stringWithFormat:@"%f",center.y] forKey:@"y"];
            [xn addObject:dic];
        }
        if ([w isEqualToString:@"南"]) {
            CGPoint center = [self setxy];
            [dic setObject:[NSString stringWithFormat:@"%f",center.x] forKey:@"x"];
            [dic setObject:[NSString stringWithFormat:@"%f",center.y] forKey:@"y"];
            [n addObject:dic];
        }
        if ([w isEqualToString:@"东南"]) {
            CGPoint center = [self setxy];
            [dic setObject:[NSString stringWithFormat:@"%f",center.x] forKey:@"x"];
            [dic setObject:[NSString stringWithFormat:@"%f",center.y] forKey:@"y"];
            [dn addObject:dic];
        }
    }
    [self insetItem];
}
#pragma mark 初始化场景模式
-(void)initCjmsView{
    _isuser = YES;
    
    
    //    mapview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 84, 84)];
    //    [_leidaView addSubview:mapview];
    la = [[UILabel alloc]initWithFrame:CGRectMake(80, 40, 40, 20)];
    la.textColor = [UIColor whiteColor];
    la.font = [UIFont systemFontOfSize:10];
    //    [_leidaView addSubview:la];
    leidaimg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 84, 84)];
    leidaimg.image = [UIImage imageNamed:@"leida"];
    [_leidaView addSubview:leidaimg];
    
    //    mapview.layer.cornerRadius = mapview.frame.size.width/2;
    //    mapview.backgroundColor = [UIColor blackColor];
    //    mapview.layer.opacity = 0.7;
    _arrowImageView = [[UIImageView alloc]initWithFrame:CGRectMake(40, 0, 39, 44)];
    _arrowImageView.image = [UIImage imageNamed:@"leidasm"];
    [_leidaView addSubview:_arrowImageView];
    
    locationManager= [[CLLocationManager alloc]init];
    locationManager.delegate = self;
    if ([CLLocationManager headingAvailable]) {
        //设置精度
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
        //设置滤波器不工作
        locationManager.headingFilter = 5;
        //开始更新
        [locationManager startUpdatingHeading];
    }
    
    // Device
    _device = [ AVCaptureDevice defaultDeviceWithMediaType : AVMediaTypeVideo ];
    // Input
    NSError *error = nil;
    _input = [ AVCaptureDeviceInput deviceInputWithDevice : self . device error : &error];
    // Output
    _output = [[ AVCaptureMetadataOutput alloc ] init ];
    [ _output setMetadataObjectsDelegate : self queue : dispatch_get_main_queue ()];
    // Session
    _session = [[ AVCaptureSession alloc ] init ];
    [ _session setSessionPreset : AVCaptureSessionPresetHigh ];
    if ([ _session canAddInput : self . input ])
    {
        [ _session addInput : self . input ];
    }
    if ([ _session canAddOutput : self . output ])
    {
        [ _session addOutput : self . output ];
    }
    // 条码类型 AVMetadataObjectTypeQRCode
    _output . metadataObjectTypes = @[ AVMetadataObjectTypeQRCode ] ;
    // Preview
    _preview =[ AVCaptureVideoPreviewLayer layerWithSession : _session ];
    _preview . videoGravity = AVLayerVideoGravityResizeAspectFill ;
    _preview . frame = self.view.frame;
    [ _pview  . layer insertSublayer : _preview atIndex : 0 ];
    //扫描区域框
    [ _session startRunning ];
    
    
    
    
}
-(CGPoint)setxy{
    CGFloat x1 = [self getRandomNumber:20 to:SCRE_WIDTH - 20];
    CGFloat y = [self getRandomNumber:140 to:SCRE_HEIGHT-200];
    return  CGPointMake(x1, y);
}
-(void)insetItem{
    for (int i=0; i<d.count; i++) {
        UIView *views = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 2, 2)];
        views.backgroundColor = [UIColor whiteColor];
        views.layer.cornerRadius = 1;
        int jd = [[[d objectAtIndex:i] objectForKey:@"jd"] intValue];
        views.tag = jd;
        CGPoint center = [self calcCircleCoordinateWithCenter:leidaimg.center andWithAngle:jd andWithRadius:20];
        views.center = CGPointMake(center.x, center.y);
        [leidaimg addSubview:views];
    }
    for (int i=0; i<db.count; i++) {
        UIView *views = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 2, 2)];
        views.backgroundColor = [UIColor whiteColor];
        views.layer.cornerRadius = 1;
        int jd = [[[db objectAtIndex:i] objectForKey:@"jd"] intValue];
        views.tag = jd;
        CGPoint center =[self calcCircleCoordinateWithCenter:leidaimg.center andWithAngle:jd andWithRadius:20];
        views.center = CGPointMake(center.x, center.y);
        [leidaimg addSubview:views];
    }
    for (int i=0; i<b.count; i++) {
        UIView *views = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 2, 2)];
        
        views.backgroundColor = [UIColor whiteColor];
        views.layer.cornerRadius = 1;
        int jd = [[[b objectAtIndex:i] objectForKey:@"jd"] intValue];
        views.tag = jd;
        CGPoint center = [self calcCircleCoordinateWithCenter:leidaimg.center andWithAngle:jd andWithRadius:20];
        views.center = CGPointMake(center.x, center.y);
        [leidaimg addSubview:views];
    }
    for (int i=0; i<xb.count; i++) {
        UIView *views = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 2, 2)];
        views.backgroundColor = [UIColor whiteColor];
        views.layer.cornerRadius = 1;
        int jd = [[[xb objectAtIndex:i] objectForKey:@"jd"] intValue];
        views.tag = jd;
        CGPoint center = [self calcCircleCoordinateWithCenter:leidaimg.center andWithAngle:jd andWithRadius:-20];
        views.center = CGPointMake(center.x, center.y);
        [leidaimg addSubview:views];
    }
    for (int i=0; i<x.count; i++) {
        UIView *views = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 2, 2)];
        views.backgroundColor = [UIColor whiteColor];
        views.layer.cornerRadius = 1;
        int jd = [[[x objectAtIndex:i] objectForKey:@"jd"] intValue];
        views.tag = jd;
        CGPoint center = [self calcCircleCoordinateWithCenter:leidaimg.center andWithAngle:jd+70 andWithRadius:-20];
        views.center = CGPointMake(center.x, center.y);
        [leidaimg addSubview:views];
    }
    for (int i=0; i<xn.count; i++) {
        UIView *views = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 2, 2)];
        views.backgroundColor = [UIColor whiteColor];
        views.layer.cornerRadius = 1;
        CGFloat jd = [[[xn objectAtIndex:i] objectForKey:@"jd"] intValue];
        views.tag = jd;
        CGPoint center = [self calcCircleCoordinateWithCenter:leidaimg.center andWithAngle:jd andWithRadius:-20];
        views.center = CGPointMake(center.x, center.y);
        [leidaimg addSubview:views];
    }
    for (int i=0; i<n.count; i++) {
        UIView *views = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 2, 2)];
        views.backgroundColor = [UIColor whiteColor];
        views.layer.cornerRadius = 1;
        int jd = [[[n objectAtIndex:i] objectForKey:@"jd"] intValue];
        views.tag = jd;
        CGPoint center = [self calcCircleCoordinateWithCenter:leidaimg.center andWithAngle:jd andWithRadius:-20];
        views.center = CGPointMake(center.x, center.y);
        [_leidaView addSubview:views];
    }
    for (int i=0; i<dn.count; i++) {
        UIView *views = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 2, 2)];
        views.backgroundColor = [UIColor whiteColor];
        views.layer.cornerRadius = 1;
        int jd = [[[dn objectAtIndex:i] objectForKey:@"jd"] intValue];
        views.tag = jd;
        CGPoint center =[self calcCircleCoordinateWithCenter:leidaimg.center andWithAngle:jd andWithRadius:-20];
        views.center = CGPointMake(center.x, center.y);
        [leidaimg addSubview:views];
    }
}

-(void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
    //每次要重置view的位置，才能保证图片每次偏转量正常，而不是叠加，指针方向正确。
    leidaimg.transform = CGAffineTransformIdentity;
    
    CGFloat headings = -1.0f * M_PI * newHeading.magneticHeading / 180;
    leidaimg.transform = CGAffineTransformMakeRotation(headings);
    CLLocationDirection jiaodu = newHeading.trueHeading;
    
    jiaodu = (int)jiaodu;
    la.text=[[NSString alloc]initWithFormat:@"%.2f",newHeading.magneticHeading];
    
    UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
    if(!UIDeviceOrientationIsPortrait(deviceOrientation)){
        return;
    }
    
    for (UIView *view in [_pview subviews]) {
        [view removeFromSuperview];
    }
    if ((jiaodu > 67 ) && (jiaodu <= 112)){//东
        for(int i= 0;i<d.count;i++){
            NSMutableArray *aryi = d;
            if (_isuser) {
                [_pview addSubview:[self addUserView:aryi i:i]];
            }else{
                [_pview addSubview:[self addServiceView:aryi i:i]];
            }
        }
    };
    if ((jiaodu > 22) && (jiaodu <= 67)) {//东北
        for(int i= 0;i<db.count;i++){
            NSMutableArray *aryi = db;
            if (_isuser) {
                [_pview addSubview:[self addUserView:aryi i:i]];
            }else{
                [_pview addSubview:[self addServiceView:aryi i:i]];
            }
        }
    };
    if ((jiaodu > 337) || (jiaodu <= 22)){//北
        NSMutableArray *aryi = b;
        for(int i= 0;i<b.count;i++){
            if (_isuser) {
                [_pview addSubview:[self addUserView:aryi i:i]];
            }else{
                [_pview addSubview:[self addServiceView:aryi i:i]];
            }
        }
    };
    if ((jiaodu > 292) && (jiaodu <= 337)) {//西北
        NSMutableArray *aryi = xb;
        for(int i= 0;i<xb.count;i++){
            if (_isuser) {
                [_pview addSubview:[self addUserView:aryi i:i]];
            }else{
                [_pview addSubview:[self addServiceView:aryi i:i]];
            }
        }
    };
    if ((jiaodu > 247) && (jiaodu <= 292)){//西
        NSMutableArray *aryi = x;
        for(int i= 0;i<x.count;i++){
            if (_isuser) {
                [_pview addSubview:[self addUserView:aryi i:i]];
            }else{
                [_pview addSubview:[self addServiceView:aryi i:i]];
            }
            
        }
    };
    if ((jiaodu > 202) && (jiaodu <= 247)){//西南
        NSMutableArray *aryi = xn;
        for(int i= 0;i<xn.count;i++){
            if (_isuser) {
                [_pview addSubview:[self addUserView:aryi i:i]];
            }else{
                [_pview addSubview:[self addServiceView:aryi i:i]];
            }
        }
    };
    if ((jiaodu > 157) && (jiaodu <= 202)){//南
        NSMutableArray *aryi = n;
        
        for(int i= 0;i<n.count;i++){
            if (_isuser) {
                [_pview addSubview:[self addUserView:aryi i:i]];
            }else{
                [_pview addSubview:[self addServiceView:aryi i:i]];
            }
        }
    };
    if ((jiaodu > 112) && (jiaodu <= 157)){//东南
        NSMutableArray *aryi = dn;
        
        for(int i= 0;i<dn.count;i++){
            if (_isuser) {
                [_pview addSubview:[self addUserView:aryi i:i]];
            }else{
                [_pview addSubview:[self addServiceView:aryi i:i]];
            }
            
        }
    };
}
#pragma mark 添加用户 item
-(UIView *)addUserView:(NSMutableArray *)aryi i:(int)i{
    UIView *bgview = [[UIView alloc]initWithFrame:CGRectMake([[[aryi objectAtIndex:i] objectForKey:@"x"] floatValue], [[[aryi objectAtIndex:i] objectForKey:@"y"] floatValue], 80, 80)];
    UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 60, 60)];
    [ValidateHelper setImage:[[aryi objectAtIndex:i] objectForKey:@"headsmall"] img:img istoux:YES];
    img.layer.cornerRadius = img.frame.size.width/2;
    img.clipsToBounds = YES;
    
    //    SphereMenu *sphereMenu = [[SphereMenu alloc] initWithStartPoint:CGPointMake([[[aryi objectAtIndex:i] objectForKey:@"x"] floatValue], )
    //                                                         startImage:img
    //                                                      submenuImages:images];
    //    sphereMenu.uid = [[aryi objectAtIndex:i] objectForKey:@"id"];
    //    sphereMenu.delegate = self;
    NSString *ds1 = [[aryi objectAtIndex:i] objectForKey:@"distance"];
    int s =[ds1 intValue]/1000;
    NSString *di = [NSString stringWithFormat:@"%d",s];
    CGSize ds = [ValidateHelper sizeOfText:[ValidateHelper DistanceFormat:di] theFont:[UIFont systemFontOfSize:14]];
    
    UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(5, 60, ds.width+10, 15)];
    lab.font = [UIFont systemFontOfSize:12];
    lab.textColor = [UIColor grayColor];
    lab.textAlignment = NSTextAlignmentCenter;
    lab.text = [ValidateHelper DistanceFormat:di];
    lab.layer.cornerRadius = 8;
    lab.clipsToBounds = YES;
    lab.layer.opacity = 0.5;
    lab.backgroundColor = colorBG;
    [bgview addSubview:lab];
    [bgview addSubview:img];
    //    [sphereMenu addSubview:lab];
    return bgview;
}
#pragma mark 添加服务 item
-(UIView *)addServiceView:(NSMutableArray *)aryi i:(int)i{
    NSString *ds1 = [[aryi objectAtIndex:i] objectForKey:@"distance"];
    int s =[ds1 intValue]/1000;
    NSString *di = [NSString stringWithFormat:@"%d",s];
    CGSize ds = [ValidateHelper sizeOfText:[ValidateHelper DistanceFormat:di] theFont:[UIFont systemFontOfSize:14]];
    
    CGSize g = [ValidateHelper sizeOfText:[[aryi objectAtIndex:i] objectForKey:@"name"] theFont:[UIFont systemFontOfSize:14]];
    BaseButton *view = [[BaseButton alloc]initWithFrame:CGRectMake([[[aryi objectAtIndex:i] objectForKey:@"x"] floatValue],[[[aryi objectAtIndex:i] objectForKey:@"y"] floatValue], ds.width+30, 60)];
    view.layer.cornerRadius = 6;
    view.dic = [aryi objectAtIndex:i];
    [view addTarget:self action:@selector(selectAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *bgview= [[UIButton alloc]initWithFrame:CGRectMake(0, 0, view.frame.size.width, 30)];
    bgview.backgroundColor = UIColorFromRGB(0x667C6D);
    
    
    //TODO:uiview 单边圆角或者单边框
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:bgview.bounds byRoundingCorners:(UIRectCornerTopRight | UIRectCornerTopLeft) cornerRadii:CGSizeMake(5,5)];//圆角大小
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = bgview.bounds;
    maskLayer.path = maskPath.CGPath;
    bgview.layer.mask = maskLayer;
    
    [view addSubview:bgview];
    
    UIImageView *bimgb = [[UIImageView alloc]initWithFrame:CGRectMake(0, 30,view.frame.size.width, 30)];
    bimgb.image = [UIImage imageNamed:@"cjxia"];
    [view addSubview:bimgb];
    
    
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, view.frame.size.width, 30)];
    title.textAlignment = NSTextAlignmentCenter;
    title.text = [[aryi objectAtIndex:i] objectForKey:@"name"];
    title.font = [UIFont systemFontOfSize:14];
    title.textColor = [UIColor whiteColor];
    [view addSubview:title];
    
    
    UIImageView *dimg = [[UIImageView alloc]initWithFrame:CGRectMake(5, 30+(30/2-12/2)/2, 11, 12)];
    dimg.image = [UIImage imageNamed:@"cjdimg"];
    [view addSubview:dimg];
    
    UILabel *distance = [[UILabel alloc]initWithFrame:CGRectMake(20, 26, ds.width, 30)];
    distance.text = [ValidateHelper DistanceFormat:di];
    distance.font = [UIFont systemFontOfSize:14];
    distance.textAlignment = NSTextAlignmentCenter;
    distance.textColor = [UIColor whiteColor];
    [view addSubview:distance];
    return view;
}


@end
